import { CACHE_KEY, DATA_FORMAT, EVENT_TYPE, getCache, setCacheByKey } from '@/utils';
import { PageContainer } from '@ant-design/pro-components';
import {
  Button,
  Card,
  Col,
  DatePicker,
  Form,
  Input,
  Modal,
  Row,
  Select,
  Table,
  Tag,
  Typography,
  notification,
} from 'antd';
import dayjs from 'dayjs';
import { cloneDeep } from 'lodash';
import React, { useState } from 'react';
import { io } from 'socket.io-client';

const Admin: React.FC = () => {
  const [data, setData] = useState(getCache(CACHE_KEY.MEETING_LIST));
  const [open, setOpen] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [editRow, setEditRow] = useState(null);
  const [form] = Form.useForm();
  const [arrangOpen, setArrangOpen] = useState(false);
  const [arrangInfo, setArrangInfo] = useState({});

  const editDataAdapter = (values) => {
    const nValues: any = {};
    Object.keys(values).forEach((key) => {
      if (key?.indexOf('time') !== -1) {
        nValues[key] = dayjs(values[key], 'YYYY-MM-DD hh:mm:ss');
      } else {
        nValues[key] = values[key];
      }
    });
    return nValues;
  };

  const onOkAdapter = (values) => {
    const nValues: any = {};
    Object.keys(values).forEach((key) => {
      if (key?.indexOf('time') !== -1) {
        nValues[key] = values[key]?.format('YYYY-MM-DD hh:mm:ss');
      } else {
        nValues[key] = values[key];
      }
    });
    return nValues;
  };

  const handleEdit = (record: any) => {
    setIsEdit(true);
    const nValues = editDataAdapter(record);
    setOpen(true);
    console.log('😈nValues', nValues);
    form.setFieldsValue(nValues);

    setEditRow(record);
  };

  const handleOk = () => {
    if (isEdit) {
      form.validateFields().then((values) => {
        console.log('😈values', values);
        const nValues = onOkAdapter(values);
        const nData = cloneDeep(data);
        nData[editRow.index] = { index: editRow.index, ...nValues };
        console.log('😈nValues', nValues);
        setData(nData);
        setOpen(false);
        form.resetFields();
      });

      return;
    }

    form.validateFields().then((values) => {
      const nValues = onOkAdapter(values);
      setData([...data, { index: data.length, ...nValues }]);
      setOpen(false);
      form.resetFields();
    });
  };

  const handleCancel = () => {
    form.resetFields();
    setOpen(false);
  };

  const columns = [
    {
      title: '申请人',
      width: 100,
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      width: 130,
      title: '单位',
      dataIndex: 'company',
      key: 'company',
    },
    {
      width: 160,
      title: '证件号',
      dataIndex: 'idNum',
      key: 'idNum',
    },
    {
      width: 100,
      title: '会见室',
      dataIndex: 'room',
      key: 'room',
    },

    {
      width: 100,
      title: '会见人',
      dataIndex: 'prisoner',
      key: 'prisoner',
    },
    {
      width: 100,
      title: '监室',
      dataIndex: 'position',
      key: 'position',
    },
    {
      width: 100,
      title: '会见状态',
      dataIndex: 'status',
      key: 'status',
      render: (_) => {
        if (_ == '待出房') return <Tag color="blue">待出房</Tag>;
        if (_ == '出房中') return <Tag color="blue">出房中</Tag>;
        if (_ == '过期取消') return <Tag color="red">过期取消</Tag>;
        if (_ == '会见完毕') return <Tag color="blue">会见完毕</Tag>;

        return <Tag>{_}</Tag>;
      },
      options: [
        { label: '在押', value: '在押' },
        { label: '出房中', value: '出房中' },
        { label: '待出房', value: '待出房' },
      ],
    },
    { width: 140, title: '申请时间', dataIndex: 'time', key: 'time' },
    {
      title: '操作',
      key: 'action',
      width: 230,
      render: (_, record) => (
        <Row gutter={10}>
          <Col>
            <Button type="primary" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          </Col>
          <Col>
            <Button
              type="primary"
              onClick={() => {
                console.log('😈record', record);
                setArrangInfo(record);
                // setTimeout(() => {
                assignMeetingRoom('会见室A', record);
                // }, 500);
                // setArrangOpen(true);
                // setArrangInfo(record);
              }}
            >
              审核通过
            </Button>
          </Col>
          {/* <Col>
            <a>会见审核</a>
          </Col>
          <Col>
            <a>分派会见室</a>
          </Col>
          <Col>
            <a>会见结束</a>
          </Col> */}
        </Row>
      ),
    },
  ];

  const assignMeetingRoom = (meetingRoom, arrangInfo) => {
    console.log('😈arrangInfo', arrangInfo);
    const vals = { ...arrangInfo, meetingRoom };
    console.log('[vals]', vals);
    notification.warning({
      duration: null,
      message: `${dayjs().format(DATA_FORMAT)}：从${vals.position}仓带${
        vals.prisoner
      }人到${meetingRoom}`,
    });
    const name = arrangInfo.prisoner;

    const nData = setCacheByKey(CACHE_KEY.MEETING_LIST, (item) => item.prisoner === name, {
      status: '待出房',
      room: '会见室A',
    });
    setData(nData);

    setCacheByKey(CACHE_KEY.PRISION_LIST, (item) => item.name === name, {
      status: '待出房',
      room: '会见室A',
    });

    setArrangOpen(false);

    const socket = io('wss://zkapi.lvseguanjia.cn:16064', {
      ackTimeout: 10000,
      retries: 3,
      auth: {
        serverOffset: 0,
      },
      port: 3000,
    });
    const clientOffset = `${socket.id}-${0}`;
    socket.emit(EVENT_TYPE.SHEN_HE_TONG_GUO, {}, clientOffset);
    const clientOffset2 = `${socket.id}-${1}`;
    socket.emit(
      EVENT_TYPE.ADD_TASK,
      {
        title: '审核通过',
        time: dayjs().format(DATA_FORMAT),
        content: '从A区201仓带东方梓涵人到会见室A',
      },
      clientOffset2,
    );
  };

  return (
    <PageContainer>
      <Modal
        open={arrangOpen}
        title="分派会议室"
        footer={null}
        onCancel={() => setArrangOpen(false)}
      >
        <Row gutter={[20, 20]} className="mt20 pad20">
          <Col span={6}>
            <Button
              type="primary"
              size="large"
              onClick={() => {
                assignMeetingRoom('会议室A');
              }}
            >
              会议室A
            </Button>
          </Col>
          <Col span={6}>
            <Button
              type="primary"
              size="large"
              onClick={() => {
                assignMeetingRoom('会议室B');
              }}
            >
              会议室B
            </Button>
          </Col>
          <Col span={6}>
            <Button
              type="primary"
              size="large"
              onClick={() => {
                assignMeetingRoom('会议室C');
              }}
            >
              会议室C
            </Button>
          </Col>
          <Col span={6}>
            <Button
              type="primary"
              size="large"
              onClick={() => {
                assignMeetingRoom('会议室D');
              }}
            >
              会议室D
            </Button>
          </Col>
        </Row>
      </Modal>

      <Modal title={isEdit ? '编辑' : '新增'} open={open} onOk={handleOk} onCancel={handleCancel}>
        <Card>
          <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 19 }}>
            {columns.map((item) => {
              if (item.key === 'action') return null;

              if (item.options)
                return (
                  <Form.Item label={item.title} name={item.key} key={item.key}>
                    <Select>
                      {item.options?.map((item) => (
                        <Select.Option key={item.value}>{item.label}</Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                );

              if (item.key?.indexOf('time') !== -1)
                return (
                  <Form.Item
                    rules={[{ required: true, message: '请选择' }]}
                    label={item.title}
                    name={item.key}
                    key={item.key}
                  >
                    <DatePicker showTime format="YYYY-MM-DD hh:mm:ss"></DatePicker>
                  </Form.Item>
                );
              return (
                <Form.Item
                  rules={[{ required: true, message: '请输入' }]}
                  label={item.title}
                  name={item.key}
                  key={item.key}
                >
                  <Input></Input>
                </Form.Item>
              );
            })}
          </Form>
        </Card>
      </Modal>
      <Card>
        <Row className="mb10">
          <Button
            type="primary"
            onClick={() => {
              setOpen(true);
              setIsEdit(false);
            }}
          >
            新增
          </Button>
        </Row>
        <Typography.Title level={2} style={{ textAlign: 'center' }}>
          <Table columns={columns} dataSource={data}></Table>
        </Typography.Title>
      </Card>
    </PageContainer>
  );
};

export default Admin;
